package com.example.loganalysis.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;

import java.util.List;
import java.util.Map;

@Service
public class TerminalSessionService {

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public TerminalSessionService(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    public List<Map<String, Object>> getTerminalSessions() throws Exception {
        String url = "http://192.168.231.60/api/v1/terminal/sessions/";
        String token = "3faf3784857fdee03007987e8f41041b4dec6302";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Token " + token);

        // 创建 HttpEntity 并发送请求
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            return objectMapper.readValue(responseBody, List.class);
        } else {
            throw new RuntimeException("Failed to fetch terminalsessions: " + response.getStatusCode());
        }
    }
}
